<template>
  <el-dialog v-model="visible" :title="`${paramsProps.title}`" :destroy-on-close="true" width="600px" draggable append-to-body>
    <el-form
      ref="ruleFormRef"
      label-width="80px"
      label-suffix=" :"
      :rules="rules"
      :model="paramsProps.row"
      @submit.enter.prevent="handleSubmit"
      class="form__label"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="paramsProps.row.username" placeholder="请填写用户名" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="昵称" prop="nickname">
            <el-input v-model="paramsProps.row.nickname" placeholder="请填写姓名" clearable />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="手机号" prop="phone">
            <el-input v-model="paramsProps.row.phone" placeholder="请填写手机号" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="性别" prop="sex">
            <el-select v-model="paramsProps.row.sex" clearable placeholder="请选择性别">
              <el-option label="未知" :value="0" />
              <el-option label="男" :value="1" />
              <el-option label="女" :value="2" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="身份证" prop="idCard">
            <el-input v-model="paramsProps.row.idCard" placeholder="请填写身份证号" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="生日" prop="birthday">
            <el-date-picker v-model="paramsProps.row.birthday" type="date" placeholder="选择生日" value-format="YYYY-MM-DD" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="paramsProps.row.email" placeholder="请填写邮箱地址" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="年龄" prop="age">
            <el-input-number v-model="paramsProps.row.age" :min="18" :max="70" placeholder="请填写年龄" />
          </el-form-item>
        </el-col>
      </el-row>
      <!-- <el-row>
        <el-col :span="12">
          <el-form-item label="状态" prop="accountStatusCd">
            <el-radio-group v-model="paramsProps.row.accountStatusCd">
              <el-radio-button v-for="item in accountStatusOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="用户标签" prop="userTagCd">
            <el-select v-model="paramsProps.row.userTagCd" clearable placeholder="请选择用户标签">
              <el-option v-for="item in userTagOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row> -->
    </el-form>
    <template #footer>
      <el-button @click="visible = false"> 取消 </el-button>
      <el-button type="primary" @click="handleSubmit"> 确定 </el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue';
import { ElMessage } from 'element-plus';
import { IS_PREVIEW } from '@/config';
import type { UserInfo } from '@/api/types/datainfo/driverUser';

defineOptions({
  name: 'DriverEdit'
});

// 账户状态选项
const accountStatusOptions = [
  { label: '正常', value: '1000001' },
  { label: '锁定', value: '1000002' },
  { label: '禁用', value: '1000003' }
];

// 用户标签选项
const userTagOptions = [
  { label: '司机', value: '1001003' },
  { label: '管理员', value: '1001001' },
  { label: '普通用户', value: '1001002' }
];

// 表单验证规则
const rules = reactive({
  username: [{ required: true, message: '请填写用户名', trigger: 'blur' }],
  nickname: [{ required: true, message: '请填写姓名', trigger: 'blur' }],
  phone: [
    { required: true, message: '请填写手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  idCard: [
    { pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: '请输入正确的身份证号', trigger: 'blur' }
  ]
});

const visible = ref(false);
const paramsProps = ref<View.DefaultParams>({
  title: '',
  row: {} as UserInfo,
  api: undefined,
  getTableList: undefined
});

// 接收父组件传过来的参数
const acceptParams = (params: View.DefaultParams) => {
  paramsProps.value = params;
  visible.value = true;
  
  // 确保数据类型正确
  if (paramsProps.value.row) {
    // 转换性别字段
    if (typeof paramsProps.value.row.sex === 'string') {
      paramsProps.value.row.sex = paramsProps.value.row.sex === '' ? 0 : parseInt(paramsProps.value.row.sex);
    }
    // 转换年龄字段
    if (typeof paramsProps.value.row.age === 'string') {
      paramsProps.value.row.age = paramsProps.value.row.age === '' ? undefined : parseInt(paramsProps.value.row.age);
    }
  }
};

// 提交数据（新增/编辑）
const ruleFormRef = ref();
const handleSubmit = () => {
  ruleFormRef.value!.validate(async (valid: boolean) => {
    if (!valid) return;
    
    if (IS_PREVIEW) {
      return ElMessage.warning({ message: '预览环境，禁止编辑司机信息，请谅解！' });
    }
    
    try {
      const data = { ...paramsProps.value.row };
      
      // 数据处理：确保数据格式正确
      if (data.sex === null || data.sex === undefined) {
        data.sex = 0;
      }
      if (data.age === null || data.age === undefined || data.age === '') {
        data.age = 0;
      }
      
      await paramsProps.value.api!(data);
      ElMessage.success({ message: `${paramsProps.value.title}成功！` });
      paramsProps.value.getTableList!();
      visible.value = false;
    } catch (error) {
      console.error('Driver edit error:', error);
      ElMessage.error('操作失败，请重试');
    }
  });
};

defineExpose({
  acceptParams
});
</script>

<style scoped lang="scss">
.form__label {
  :deep(.el-form-item__label) {
    font-weight: 500;
  }
}
</style>